﻿using DataImporter.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataImporter.Modules
{
    public partial class ucTNB : UserControl
    {
        private List<LTHR> lTHRs = new List<LTHR>();

        public ucTNB()
        {
            InitializeComponent();
            this.cbbDropdown.SelectedIndex = 0;
        }

        private DBContext DBContext => new DBContext();

        private void ofdFile_FileOk(object sender, CancelEventArgs e)
        {
            var name = this.cbbDropdown.SelectedIndex > 1 ? this.cbbDropdown.Items[1].ToString() : this.cbbDropdown.SelectedItem.ToString();
            var table = this.ofdFile.FileName.GetDataTable(name);
            if (this.cbbDropdown.SelectedIndex == 0)
                HandleFirst(table);
            else if (this.cbbDropdown.SelectedIndex == 1)
                HandleSecond(table);
            else if (this.cbbDropdown.SelectedIndex == 2)
                HandleThird(table);
            else
                HandleFourth(table);
        }

        public void HandleFourth(DataTable table)
        {
            var scores = new List<T2DMScores>();

            for (int i = 5; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];

                var score = row[21].ToString();

                if (score.IsNullOrEmpty())
                    break;

                scores.Add(new T2DMScores
                {
                    Score = int.Parse(score.Replace("−", "-")),
                    RiskScore = float.Parse(row[22].ToString()),
                });
            }

            this.dgvData.DataSource = scores;
        }

        private void HandleThird(DataTable table)
        {
            var risks = new List<T2DMRisk>();
            int order = 0;
            for (int i = 5; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];
                var rule = row[5].ToString();

                if (rule.IsNullOrEmpty())
                    break;

                risks.Add(new T2DMRisk
                {
                    Name = row[1].ToString(),
                    MaleAverage = float.Parse(row[6].ToString()),
                    MaleRiseNumber = float.Parse(row[7].ToString()),
                    MaleAge = float.Parse(row[11].ToString()),
                    FemaleAverage = float.Parse(row[14].ToString()),
                    FemaleRiseNumber = float.Parse(row[15].ToString()),
                    FemaleAge = float.Parse(row[19].ToString()),
                    Rule = rule,
                    Order = order += 5
                });
            }

            this.dgvData.DataSource = risks;
        }

        private void HandleFirst(DataTable table)
        {
            var order = 0;
            for (int i = 0; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];
                var item = new LTHR
                {
                    Category = row["分类"].ToString(),
                    Code = row["编码"].ToString().Trim(),
                    Name = row["体检名称"].ToString(),
                    Order = order += 5,
                    Product = row["产品"].ToString(),
                    ShortName = row["简称"].ToString(),
                    Unit = row["单位"].ToString()
                };
                if (item.Name.IsNullOrEmpty())
                    continue;
                lTHRs.Add(item);
            }
            this.dgvData.DataSource = lTHRs;
        }

        private void HandleSecond(DataTable table)
        {
            var lst = new List<T2DM>();
            var id = 0;
            T2DM parent = null;
            for (int i = 4; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];
                if (row[0].IsNullOrEmpty())
                    continue;
                var type = row[2].ToString();
                var rule = row[5].ToString();
                var peCode = row[3].ToString().Trim();
                DyncmicRuntime.Compute(rule.Replace("v", "3").Replace("age", "31"));
                lst.Add(new T2DM
                {
                    Id = ++id,
                    Code = row[0].ToString().Trim(),
                    Name = row[1].ToString(),
                    PECode = peCode,
                    Score = int.TryParse(row[4].ToString(), out var score) ? score : 0,
                    Type = type.IsNullOrEmpty() ? 0 : int.Parse(type),
                    Rule = row[5].ToString()
                });
                if (!type.IsNullOrEmpty())
                    parent = lst.Last();
                else
                    lst.Last().ParentId = parent.Id;
            }

            this.dgvData.DataSource = lst;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            this.ofdFile.ShowDialog();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.cbbDropdown.SelectedIndex == 0)
            {
                if (!DBContext.Db.DbMaintenance.IsAnyTable(nameof(LTHR)))
                    DBContext.Db.CodeFirst.InitTables<LTHR>();
                DBContext.Db.DbMaintenance.TruncateTable<LTHR>();
                DBContext.LTHRDB.InsertRange(lTHRs);
            }
            else if (this.cbbDropdown.SelectedIndex == 1)
            {
                if (DBContext.Db.DbMaintenance.IsAnyTable(nameof(T2DM)))
                    DBContext.Db.DbMaintenance.DropTable(nameof(T2DM));
                DBContext.Db.CodeFirst.InitTables<T2DM>();
                DBContext.Db.DbMaintenance.TruncateTable<T2DM>();
                DBContext.T2DMDB.InsertRange((List<T2DM>)this.dgvData.DataSource);
            }
            else if (this.cbbDropdown.SelectedIndex == 2)
            {
                if (DBContext.Db.DbMaintenance.IsAnyTable(nameof(T2DMRisk)))
                    DBContext.Db.DbMaintenance.TruncateTable<T2DMRisk>();
                DBContext.Db.CodeFirst.InitTables<T2DMRisk>();
                DBContext.T2DMRiskDB.InsertRange((List<T2DMRisk>)this.dgvData.DataSource);
            }
            else
            {
                DBContext.Db.CodeFirst.InitTables<T2DMScores>();
                DBContext.Db.DbMaintenance.TruncateTable<T2DMScores>();
                DBContext.T2DMScoresDB.InsertRange((List<T2DMScores>)this.dgvData.DataSource);
            }
            MessageBox.Show("保存成功");
        }
    }
}
